import type { ResponsePaginationData } from '@/utils/request';
import { SUCCESS_CODE } from '@/utils/request';
import type { RequestData } from '@ant-design/pro-table';
import type {
  AuthPermission,
  AuthPermissionAddItem,
  AuthPermissionEditItem,
  AuthPermissionTableListItem,
} from '@/pages/Auth/AuthPermission/data';
import { request } from 'umi';
import { message } from 'antd';

/**
 * 获取权限列表
 * @param params
 */
export async function queryAdminAccessList(
  params: Pagination & { name?: string },
): Promise<RequestData<AuthPermissionTableListItem>> {
  try {
    const res: ResponsePaginationData<AuthPermission> = await request('/sys/permission/page', {
      params: {
        current: params.current,
        size: params.pageSize,
        name: params.name,
      },
    });

    if (res?.code !== SUCCESS_CODE) {
      return { success: false, total: 0, data: [] };
    }

    return {
      success: res.code === SUCCESS_CODE,
      total: res.data?.total,
      data: res.data?.list,
    };
  } catch (error) {
    message.error('服务器请求失败，请重试，如果多次请求失败，请联系管理员');
    throw error;
  }
}

/**
 * 创建一个权限
 * @param params
 */
export async function addAdminAccess(params: AuthPermissionAddItem) {
  const { name, code } = params;
  try {
    const res = request('/sys/permission/', {
      method: 'POST',
      data: { code: code, name },
    });
    return res;
  } catch (error) {
    message.error('服务器请求失败，请重试，如果多次请求失败，请联系管理员');
    throw error;
  }
}

/**
 * 获取单个权限字典详情
 * @param params
 */
export async function getPermission(params: { id: string }) {
  try {
    const res = await request(`/sys/permission`, { params: { ...params } });
    if (res.code === SUCCESS_CODE) {
      return res.data;
    }
    return res;
  } catch (error) {
    message.error('服务器请求失败，请重试，如果多次请求失败，请联系管理员');
    throw error;
  }
}

/**
 * 修改权限条目
 * @param params
 */
export async function editPermission(params: AuthPermissionEditItem): Promise<AuthPermission> {
  try {
    const res = request(`/sys/permission/update_permission`, {
      method: 'POST',
      data: params,
    });
    return res;
  } catch (error) {
    message.error('服务器请求失败，请重试，如果多次请求失败，请联系管理员');
    throw error;
  }
}

/**
 * 删除权限字典
 * @param params
 */
export async function removePermission(params: AuthPermission) {
  try {
    const res = await request('/sys/permission/delete', {
      method: 'POST',
      params: {
        id: params.id,
        name: params.name,
      },
    });
    if (res.code === SUCCESS_CODE) {
      return res.data;
    }
    return res;
  } catch (error) {
    message.error('服务器请求失败，请重试，如果多次请求失败，请联系管理员');
    throw error;
  }
}
